<template>
	<el-form :model="detailForm" ref="detailForm" :inline="false">
		<el-card class="box-card" shadow="never">
			<div slot="header" class="header-card">
				<span class="header-card-title">上传保单</span>
			</div>
			<el-row>
				<el-col>
					<el-form-item>
						<el-button
							type="primary"
              v-if="isEdit"
							size="small"
							:disabled="insuranceVoList.length === 0"
							@click="handleBatch">
							批量处理时间
						</el-button>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row :gutter="24">
				<el-col :span="24">
					<el-table
						ref="multipleTable"
						:data="detailForm.insuranceVoList"
						border
						tooltip-effect="dark"
						style="width: 100%"
						@selection-change="handleSelectionChange">
						<el-table-column v-if="isEdit" fixed="left" type="selection" width="40" />
            <el-table-column
                v-if="isEdit"
                align="center"
                label="操作"
                width="50"
                fixed="left">
              <template #default="{ row, $index }">
                <el-button
                    size="mini"
                    type="text"
                    @click="handleEdit(row, $index)">
                  编辑
                </el-button>
              </template>
            </el-table-column>
            <el-table-column
                align="center"
                label="车架号"
                prop="vinNo"
                fixed="left"
                min-width="180" />
            <el-table-column
                align="center"
                label="车牌号"
                prop="carNo"
                min-width="180" />

						<el-table-column
							align="center"
							label="品牌/车型"
							show-overflow-tooltip
							prop="carNo"
							min-width="280">
							<template #default="{ row }">
								{{ row.brandName
								}}{{ row.modelName ? '/' + row.modelName : '' }}
							</template>
						</el-table-column>

						<el-table-column
							align="center"
							label="商业险实际开始时间"
							prop="syxActualBeginTime"
							min-width="180">
							<template #default="{ row, $index }">
								<el-form-item
									class="formTable"
									:prop="
										'insuranceVoList.' +
										$index +
										'.syxActualBeginTime'
									"
									:rules="{
										required: isEdit,
										trigger: 'blur',
									}">
									<el-date-picker
										@change="
											changeData(
												detailForm.insuranceVoList,
												row.syxActualBeginTime,
												$index,
												'syxActualEndTime',
											)
										"
										v-model="row.syxActualBeginTime"
										type="date"
										placeholder="请选择商业险实际开始时间"
										v-if="isEdit"
										value-format="yyyy-MM-dd"
										style="width: 100%"></el-date-picker>

									<span v-else>
										{{ row.syxActualBeginTime }}
									</span>
								</el-form-item>
							</template>
						</el-table-column>

						<el-table-column
							align="center"
							label="商业险实际结束时间"
							min-width="180"
							prop="syxActualEndTime">
							<template #default="{ row, $index }">
								<el-form-item
									class="formTable"
									:prop="
										'insuranceVoList.' +
										$index +
										'.syxActualEndTime'
									"
									:rules="{
										required: isEdit,
										trigger: 'blur',
									}">
									<el-date-picker
										v-model="row.syxActualEndTime"
										type="date"
										placeholder="请选择商业险实际结束时间"
										v-if="isEdit"
										value-format="yyyy-MM-dd"
										style="width: 100%"></el-date-picker>
									<span v-else>
										{{ row.syxActualEndTime }}
									</span>
								</el-form-item>
							</template>
						</el-table-column>

						<el-table-column
							align="center"
							label="商业险保单号"
							prop="syxPolicyCode"
							min-width="160">
							<template #default="{ row, $index }">
								<el-form-item
									class="formTable"
									:prop="
										'insuranceVoList.' +
										$index +
										'.syxPolicyCode'
									"
									:rules="{
										required: isEdit,
										trigger: 'blur',
									}">
									<el-input
										v-if="isEdit"
										v-model="row.syxPolicyCode"
										@change="
											handlePolicyCode(
												row.syxPolicyCode,
												$index,
												'syxPolicyCode',
												'jqxPolicyCode',
											)
										"
										placeholder="请输入商业险保单号"
										size="mini" />
									<span v-else>{{ row.syxPolicyCode }}</span>
								</el-form-item>
							</template>
						</el-table-column>

						<el-table-column
							align="center"
							label="交强险实际开始时间"
							prop="jqxActualBeginTime"
							min-width="180">
							<template #default="{ row, $index }">
								<el-form-item
									class="formTable"
									:prop="
										'insuranceVoList.' +
										$index +
										'.jqxActualBeginTime'
									"
									:rules="{
										required: isEdit,
										trigger: 'blur',
									}">
									<el-date-picker
										@change="
											changeData(
												detailForm.insuranceVoList,
												row.jqxActualBeginTime,
												$index,
												'jqxActualEndTime',
											)
										"
										v-model="row.jqxActualBeginTime"
										type="date"
										placeholder="请选择交强险起保日"
										v-if="isEdit"
										value-format="yyyy-MM-dd"
										style="width: 100%"></el-date-picker>
									<span v-else>
										{{ row.jqxActualBeginTime }}
									</span>
								</el-form-item>
							</template>
						</el-table-column>

						<el-table-column
							align="center"
							label="交强险实际结束时间"
							prop="jqxActualEndTime"
							min-width="180">
							<template #default="{ row, $index }">
								<el-form-item
									class="formTable"
									:prop="
										'insuranceVoList.' +
										$index +
										'.jqxActualEndTime'
									"
									:rules="{
										required: isEdit,
										trigger: 'blur',
									}">
									<el-date-picker
										v-model="row.jqxActualEndTime"
										type="date"
										placeholder="请选择交强险到期日"
										v-if="isEdit"
										value-format="yyyy-MM-dd"
										style="width: 100%"></el-date-picker>
									<span v-else>
										{{ row.jqxActualEndTime }}
									</span>
								</el-form-item>
							</template>
						</el-table-column>

						<el-table-column
							align="center"
							label="交强险保单号"
							prop="jqxPolicyCode"
							min-width="180">
							<template #default="{ row, $index }">
								<el-form-item
									class="formTable"
									:prop="
										'insuranceVoList.' +
										$index +
										'.jqxPolicyCode'
									"
									:rules="{
										required: isEdit,
										trigger: 'blur',
									}">
									<el-input
										v-if="isEdit"
										v-model="row.jqxPolicyCode"
										@change="
											handlePolicyCode(
												row.jqxPolicyCode,
												$index,
												'jqxPolicyCode',
												'syxPolicyCode',
											)
										"
										placeholder="请输入交强险保单号"
										size="mini" />
									<span v-else>{{ row.jqxPolicyCode }}</span>
								</el-form-item>
							</template>
						</el-table-column>

						<el-table-column
							align="center"
							label="商业险保单"
							width="200">
							<template #default="{ row }">
								<el-popover placement="right" trigger="click">
									<image-common
										v-model="row.syxPolicyUrl"
										:disabled="!isEdit"
										:up-type="2" />
									<el-button type="text" slot="reference">
										<span
											v-if="row.syxBool"
											style="
												color: red;
												padding-left: 20px;
											">
											请上传商业险保单
										</span>
										<span v-else>{{row.syxPolicyUrl ? '查看' : '上传'}}</span>
									</el-button>
								</el-popover>
							</template>
						</el-table-column>

						<el-table-column
							align="center"
							label="交强险保单"
							width="200">
							<template #default="{ row }">
								<el-popover placement="right" trigger="click">
									<image-common
										v-model="row.jqxPolicyUrl"
										:disabled="!isEdit"
										:up-type="2" />
									<el-button type="text" slot="reference">
										<span
											v-if="row.jqxBool"
											style="
												color: red;
												padding-left: 20px;
											">
											请上传交强险保单
										</span>
										<span v-else>{{row.jqxPolicyUrl ? '查看' : '上传'}}</span>
									</el-button>
								</el-popover>
							</template>
						</el-table-column>
					</el-table>
				</el-col>
			</el-row>
		</el-card>

		<el-dialog
			:title="title"
			:visible.sync="open"
			width="800px"
			append-to-body>
			<el-form
				ref="form"
				:model="form"
				class="dialogForm"
				:rules="rules"
				label-width="160px">
				<el-row v-if="title === '编辑'">
					<el-col :span="12">
						<el-form-item label="车架号:" prop="vinNo">
							<span>{{ form.vinNo }}</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="车牌号:" prop="carNo">
							<span>{{ form.carNo }}</span>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row v-if="title === '编辑'">
					<el-col :span="12">
						<el-form-item
							label="商业险保单号:"
							prop="syxPolicyCode">
							<!-- @change="handleChange(form.syxPolicyCode,'syxPolicyCode')"-->
							<el-input
								v-if="isEdit"
								v-model="form.syxPolicyCode"
								placeholder="请输入商业险保单号"
								size="mini" />
							<span v-else>{{ form.syxPolicyCode }}</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item
							label="交强险保单号:"
							prop="jqxPolicyCode">
							<!-- @change="handleChange(form.jqxPolicyCode,'jqxPolicyCode')"-->
							<el-input
								v-if="isEdit"
								v-model="form.jqxPolicyCode"
								placeholder="请输入交强险保单号"
								size="mini" />
							<span v-else>{{ form.jqxPolicyCode }}</span>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row>
					<el-col :span="12">
						<el-form-item
							label="商业实际开始时间:"
							prop="syxActualBeginTime">
							<el-date-picker
								v-model="form.syxActualBeginTime"
								type="date"
								@change="
									handleDialogDate(
										form.syxActualBeginTime,
										'syxActualEndTime',
									)
								"
								placeholder="请选择商业实际开始使时间"
								value-format="yyyy-MM-dd"
								style="width: 100%"></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item
							label="商业实际结束使时间:"
							prop="syxActualEndTime">
							<el-date-picker
								v-model="form.syxActualEndTime"
								type="date"
								placeholder="请选择商业实际结束使时间"
								value-format="yyyy-MM-dd"
								style="width: 100%"></el-date-picker>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row>
					<el-col :span="12">
						<el-form-item
							label="交强实际开始使时间:"
							prop="jqxActualBeginTime">
							<el-date-picker
								@change="
									handleDialogDate(
										form.jqxActualBeginTime,
										'jqxActualEndTime',
									)
								"
								v-model="form.jqxActualBeginTime"
								type="date"
								placeholder="请选择交强实际开始使时间"
								value-format="yyyy-MM-dd"
								style="width: 100%"></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item
							label="交强实际结束使时间:"
							prop="jqxActualEndTime">
							<el-date-picker
								v-model="form.jqxActualEndTime"
								type="date"
								placeholder="请选择交强实际结束使时间"
								value-format="yyyy-MM-dd"
								style="width: 100%"></el-date-picker>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row v-if="title === '编辑'">
					<el-col :span="12">
						<el-form-item label="商业险保单:" prop="syxPolicyUrl">
							<image-common
								v-model="form.syxPolicyUrl"
								:limit="20"
								:disabled="!isEdit"
								:upType="2" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="交强险保单:" prop="jqxPolicyUrl">
							<image-common
								v-model="form.jqxPolicyUrl"
								:limit="20"
								:disabled="!isEdit"
								:upType="2" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="cancel">取 消</el-button>
				<el-button type="primary" @click="submitForm">确 定</el-button>
			</div>
		</el-dialog>
	</el-form>
</template>

<script>
	import { effectDate } from '@/utils/libs/effectDate.js';
	import { Empty } from '@/utils/utils';

	export default {
		name: 'uploadPolicy', //上传保单（保司）
		props: {
			value: {
				type: Object,
				default: {},
			},
			state: {
				type: String,
				default: '',
			},
			activityId: {
				type: String,
				default: '',
			},
			pageConfig: {
				type: Array,
				default: () => {
					return [];
				},
			},
		},

		computed: {
			detailForm: {
				get() {
					let that = this;
					const proxy = new Proxy(that.value, {
						get(target, key) {
							return Reflect.get(target, key);
						},
						set(target, key, value) {
							that.$emit('input', { ...target, [key]: value });
							return true;
						},
					});
					return proxy;
				},
			},
			isEdit() {
				let bool;
				switch (this.state) {
					case 'write':
						bool = true;
						break;
					case 'disabled':
						bool = false;
						break;
					case 'readonly':
						bool = false;
						break;
				}
				return bool;
			},
		},
		watch: {
			'value.insuranceVoList': {
				handler(val) {
					if (val) {
						val.forEach(item => {
							if (item.syxPolicyUrl) {
								item.syxBool = false;
							}
							if (item.jqxPolicyUrl) {
								item.jqxBool = false;
							}
						});
					}
				},
				immediate: true,
				deep: true,
			},
		},
		data() {
			var jqxStart = (rule, value, callback) => {
				let that = this;
				effectDate(
					rule,
					value,
					callback,
					that.form.jqxActualBeginTime,
					that.form.jqxActualEndTime,
					'交强险起保日',
					'交强险到期日',
				);
			};
			var jqxEnd = (rule, value, callback) => {
				let that = this;
				effectDate(
					rule,
					value,
					callback,
					that.form.jqxActualBeginTime,
					that.form.jqxActualEndTime,
					'交强险起保日',
					'交强险到期日',
				);
			};
			var syxStart = (rule, value, callback) => {
				let that = this;
				effectDate(
					rule,
					value,
					callback,
					that.form.syxActualBeginTime,
					that.form.syxActualEndTime,
					'商业险起保日',
					'商业险到期日',
				);
			};
			var syxEnd = (rule, value, callback) => {
				let that = this;
				effectDate(
					rule,
					value,
					callback,
					that.form.syxActualBeginTime,
					that.form.syxActualEndTime,
					'商业险起保日',
					'商业险到期日',
				);
			};

			var syxCode = (rule, value, callback) => {
				let that = this;
				if (value === ' ' || value === null) {
					callback(new Error('请输入保单号'));
				} else {
					let index_ = this.value.insuranceVoList.findIndex(
						(item, i) =>
							(i !== that.index &&
								value === item.syxPolicyCode) ||
							value === item.jqxPolicyCode,
					);
					if (index_ !== -1) {
						callback(new Error('商业险保单号冲突,请核实'));
					} else {
						callback();
					}
				}
			};

			var jaxCode = (rule, value, callback) => {
				let that = this;
				if (value === ' ' || value === null) {
					callback(new Error('请输入保单号'));
				} else {
					let index_ = this.value.insuranceVoList.findIndex(
						(item, i) =>
							(i !== that.index &&
								value === item.jqxPolicyCode) ||
							value === item.syxPolicyCode,
					);
					if (index_ !== -1) {
						callback(new Error('交强险保单号冲突,请核实'));
					} else {
						callback();
					}
				}
			};
			return {
				title: '',
				obj: {},
				open: false,
				form: {},
				rules: {
					syxPolicyCode: [
						{ required: true, validator: syxCode, trigger: 'blur' },
					],
					jqxPolicyCode: [
						{ required: true, validator: jaxCode, trigger: 'blur' },
					],
					syxPolicyUrl: [
						{
							required: true,
							message: '请上传商业险保单',
							trigger: 'blur',
						},
					],
					jqxPolicyUrl: [
						{
							required: true,
							message: '请上传交强险保单',
							trigger: 'blur',
						},
					],

					syxActualBeginTime: [
						{
							required: true,
							validator: syxStart,
							trigger: 'blur',
						},
					],
					syxActualEndTime: [
						{ required: true, validator: syxEnd, trigger: 'blur' },
					],
					jqxActualBeginTime: [
						{
							required: true,
							validator: jqxStart,
							trigger: 'blur',
						},
					],
					jqxActualEndTime: [
						{ required: true, validator: jqxEnd, trigger: 'blur' },
					],
				},
				index: 0,
				insuranceVoList: [],
				activityName: '',
				shopInsuranceBool: false, //店保
				ourCompanyBool1: false, //我司
				ourCompanyBool2: false, //我司
				formId: '',
			};
		},
		created() {
			this.$nextTick(() => {
				this.handleTime(
					this.value.jqxExpectBeginTime,
					this.value.jqxExpectEndTime,
					this.value.syxExpectBeginTime,
					this.value.syxExpectEndTime,
				);
			});
		},

		methods: {
			handleTime(syxStart, syxEnd, jqxStart, jqxEnd) {
				this.value.insuranceVoList.forEach(item => {
					item.syxActualBeginTime = syxStart;
					item.syxActualEndTime = syxEnd;
					item.jqxActualBeginTime = jqxStart;
					item.jqxActualEndTime = jqxEnd;
				});
			},

			handleChange(val, key) {
				if (val) {
					if (key === 'syxPolicyCode') {
						if (val === this.form.jqxPolicyCode) {
							this.form.syxPolicyCode = '';
						} else {
							this.form.syxPolicyCode = val;
						}
					}

					if (key === 'jqxPolicyCode') {
						if (val === this.form.syxPolicyCode) {
							this.form.jqxPolicyCode = '';
						} else {
							this.form.jqxPolicyCode = val;
						}
					}
				}
			},

			handlePolicyCode(val, i, key, key_) {
				if (val) {
					this.handleRepeat(i, key, val, key_);
				}
			},

			handleRepeat(index, key, val, key_) {
				let index_ = this.value.insuranceVoList.findIndex(
					(item, i) =>
						(i !== index && val === item[key]) ||
						val === item[key_],
				);
				if (index_ !== -1) {
					this.$set(this.value.insuranceVoList[index], [key], '');
				} else {
					this.$set(this.value.insuranceVoList[index], [key], val);
				}
			},

			handleDialogDate(time, key) {
				let timeDate = this.addOneMonth(time, 12);
				this.$set(this.form, [key], timeDate);
			},

			changeData(list, time, i, key) {
				let timeDate = this.addOneMonth(time, 12);
				this.$set(this.detailForm.insuranceVoList, i, {
					...this.detailForm.insuranceVoList[i],
					[key]: timeDate,
				});
			},

			addOneMonth(dateString, month) {
				const date = new Date(dateString);
				date.setMonth(date.getMonth() + Number(month));
				date.setDate(date.getDate() - 1);
				return date.toISOString().split('T')[0]; // 返回YYYY-MM-DD格式的日期字符串
			},

			handleBatch() {
				if (this.insuranceVoList.length > 0) {
					this.title = '批量编辑保单时间';
					this.form = {
						syxActualBeginTime: '',
						syxActualEndTime: '',
						jqxActualBeginTime: '',
						jqxActualEndTime: '',
					};
					this.open = true;
				}
			},

			handleSelectionChange(val) {
				this.insuranceVoList = val.map(a => {
					return a.workId;
				});
			},

			handleEdit(row, index) {
				this.title = '编辑';
				this.open = true;
				this.form = row;
				this.index = index;
			},

			cancel() {
				this.open = false;
				this.form = {};
			},

			submitForm() {
				this.$refs.form.validate(valid => {
					if (valid) {
						if (this.title === '编辑') {
							this.detailForm.insuranceVoList[this.index] =
								this.form;
						}
						if (this.title === '批量编辑保单时间') {
							for (
								let i = 0;
								i < this.insuranceVoList.length;
								i++
							) {
								let indexL =
									this.detailForm.insuranceVoList.findIndex(
										a =>
											a.workId ===
											this.insuranceVoList[i],
									);
								if (indexL !== -1) {
									this.detailForm.insuranceVoList[
										indexL
									].syxActualBeginTime =
										this.form.syxActualBeginTime;
									this.detailForm.insuranceVoList[
										indexL
									].syxActualEndTime =
										this.form.syxActualEndTime;
									this.detailForm.insuranceVoList[
										indexL
									].jqxActualBeginTime =
										this.form.jqxActualBeginTime;
									this.detailForm.insuranceVoList[
										indexL
									].jqxActualEndTime =
										this.form.jqxActualEndTime;
								}
							}
						}
						this.open = false;
					}
				});
			},

			valid() {
				let arr = [
					this.handleUrl(
						this.value.insuranceVoList,
						'syxPolicyUrl',
						'syxBool',
					),
					this.handleUrl(
						this.value.insuranceVoList,
						'jqxPolicyUrl',
						'jqxBool',
					),
				];

				return new Promise((resolve, reject) => {
					this.$refs.detailForm.validate(valid => {
						Promise.all(arr)
							.then(() => {
								resolve(valid && true);
							})
							.catch(() => {
								resolve(valid && false);
							});
					});
				});
			},

			handleUrl(list, key, str) {
				return new Promise((resolve, reject) => {
					let boole;
					list.forEach((item, index) => {
						if (item[key]) {
							this.$set(list[index], [str], false);
						} else {
							this.$set(list[index], [str], true);
						}
					});
					boole = list.every(
						item =>
							item.syxBool === false && item.jqxBool === false,
					);
					if (boole) {
						resolve();
					} else {
						reject();
					}
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	@import '@/styles/cwgd/formScss.scss';

	::v-deep.el-opover-img {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 0;
	}

	::v-deep.component-upload-image {
		margin-left: 25px !important;
	}
</style>
